package com.cskaoyan.order.service.impl;

import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.form.OrderListRequest;
import com.cskaoyan.order.service.OrderCoreService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderConverter orderConverter;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public String createOrder(CreateOrderRequest request) {
        //创建pipeline对象
        TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

        //启动pipeline
        invoker.start(); //启动流程（pipeline来处理）

        //获取处理结果
        AbsTransHandlerContext context = invoker.getContext();

        //从Context中获取订单Id
        String orderId = context.getOrderId();
        return orderId;
    }

    /**
     * 取消订单的业务逻辑
     *
     * @param orderId
     * @return void
     * @author gatsby
     * @since 2022/10/26 16:08
     */
    @Override
    public void cancelOrder(String orderId) {
        //修改订单对应的状态
        orderMapper.updateStatusByOrderId(orderId);
        //将商品数量添加到商品库存中
        //1.查询出该订单对应的全部商品
        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        for (OrderItem orderItem : orderItems) {
            // 2.更新商品库存表中商品对应的库存
            Stock stock = new Stock();
            stock.setLockCount(-orderItem.getNum());
            stock.setStockCount(orderItem.getNum().longValue());
            stock.setItemId(orderItem.getItemId());
            stockMapper.updateStock(stock);
        }
    }

    /**
     * 删除订单的业务逻辑
     *
     * @param orderId
     * @return void
     * @author gatsby
     * @since 2022/10/26 16:33
     */
    @Override
    public void deleteOrder(String orderId) {
        //删除订单表中对应的记录
        orderMapper.deleteOrderByOrderId(orderId);
        //删除订单关联表中对应的记录
        orderItemMapper.deleteByOrderId(orderId);
        orderShippingMapper.deleteByOrderId(orderId);

    }

    @Override
    public void updateOrder(Integer status, String orderId) {
    }

    /**
     * 查询用户的全部订单
     *
     * @param orderListRequest
     * @return com.cskaoyan.order.dto.OrderListResponse
     * @author gatsby
     * @since 2022/10/26 11:44
     */
    @Override
    public OrderListResponse queryAllOrder(OrderListRequest orderListRequest) {

        //查询出全部的数据
        //Integer total=orderMapper.countByUserId(orderListRequest.getUserId());

        //开启分页
        PageHelper.startPage(orderListRequest.getPage(), orderListRequest.getSize());
        //查询商品
        Example example = new Example(Order.class);
        example.setOrderByClause("create_time desc");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", orderListRequest.getUserId());
        
        List<Order> orderList = orderMapper.selectByExample(example);
        // Page<Order> orderList = (Page<Order>) orderMapper.selectByExample(example);
        // long total = orderList.getTotal();
        List<OrderDetailInfo> orderDetailInfos = orderConverter.order2details(orderList);
        List<OrderDetailInfo> orderDetailInfoList = new ArrayList<>();
        if (orderDetailInfos != null) {
            for (OrderDetailInfo orderDetailInfo : orderDetailInfos) {
                //根据订单id查找对应的商品信息
                List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderDetailInfo.getOrderId());
                List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
                //塞进去订单关联的商品信息
                orderDetailInfo.setOrderItemDto(orderItemDtos);

                //根据订单id查找对应的地址信息
                Example example1 = new Example(OrderShipping.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("orderId", orderDetailInfo.getOrderId());
                List<OrderShipping> orderShippings = orderShippingMapper.selectByExample(example1);
                OrderShipping orderShipping = orderShippings.get(0);
                OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
                //塞进去订单关联的的地址信息
                orderDetailInfo.setOrderShippingDto(orderShippingDto);

                orderDetailInfoList.add(orderDetailInfo);

            }
        }
        OrderListResponse orderListResponse = new OrderListResponse();
        orderListResponse.setData(orderDetailInfoList);
        Integer size = orderDetailInfoList.size();
        PageInfo<Order> orderPageInfo = new PageInfo<>(orderList);
        long total1 = orderPageInfo.getTotal();
        //orderListResponse.setTotal(total.longValue());
        orderListResponse.setTotal(total1);
        return orderListResponse;
    }

    /**
     * 根据订单id查询对应的详情信息
     *
     * @param id
     * @return com.cskaoyan.order.dto.OrderDetailResponse
     * @author gatsby
     * @since 2022/10/26 15:38
     */
    @Override
    public OrderDetailResponse queryOrderDetail(String id) {
        //OrderDetailResponse orderDetailResponse = new OrderDetailResponse();

        //查询order的信息
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", id);
        List<Order> orderList = orderMapper.selectByExample(example);
        Order order = null;
        if (orderList != null && orderList.size()>0) {
            order = orderList.get(0);
        }

        //查询shipping的信息
        Example example1 = new Example(OrderShipping.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("orderId", id);
        List<OrderShipping> orderShippings = orderShippingMapper.selectByExample(example1);
        OrderShipping orderShipping = null;
        if (orderShippings != null) {
            orderShipping = orderShippings.get(0);
        }

        OrderDetailResponse orderDetailResponse = orderConverter.order2res(order, orderShipping);
        //根据订单id查询出对应的商品
        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(id);
        List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
        orderDetailResponse.setGoodsList(orderItemDtos);
        return orderDetailResponse;
    }

}
